package com.zrrd.mcl.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.mcl.model.product.BaseAttrInfo;
import com.zrrd.mcl.model.product.BaseAttrValue;
import com.zrrd.mcl.product.mapper.BaseAttrInfoMapper;
import com.zrrd.mcl.product.mapper.BaseAttrValueMapper;
import com.zrrd.mcl.product.service.BaseAttrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BaseAttrServiceImpl extends ServiceImpl<BaseAttrInfoMapper, BaseAttrInfo> implements BaseAttrService {

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    //根据分类id查询平台属性以及属性值
    @Override
    public List<BaseAttrInfo> selectBaseAttrInfoList(Long category1Id, Long category2IdId, Long category3Id) {
        return baseAttrInfoMapper.selectBaseAttrInfoList(category1Id, category2IdId, category3Id);
    }

    //添加平台属性
    @Override
    @Transactional
    public void saveBaseAttrInfo(BaseAttrInfo baseAttrInfo) {
        //判断是修改还是添加
        if (baseAttrInfo.getId() != null) {
            this.updateById(baseAttrInfo);
        } else {
            //保存平台属性
            this.save(baseAttrInfo);
        }

        QueryWrapper<BaseAttrValue> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_id", baseAttrInfo.getId());
        baseAttrValueMapper.delete(wrapper);

        //获取传递过来的属性值集合
        List<BaseAttrValue> baseAttrValues = baseAttrInfo.getAttrValueList();
        if (baseAttrValues != null && baseAttrValues.size() > 0) {
            for (BaseAttrValue baseAttrValue : baseAttrValues) {
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(baseAttrValue);
            }
        }

    }

    //根据属性id查询属性
    @Override
    public List<BaseAttrValue> getAttrInfo(Long attrId) {
        QueryWrapper<BaseAttrValue> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_id", attrId);
        List<BaseAttrValue> valueList = baseAttrValueMapper.selectList(wrapper);
        return valueList;
    }

    @Override
    public List<BaseAttrInfo> selectBaseAttrInfoListBySkuId(Long skuId) {
        return baseAttrInfoMapper.selectBaseAttrInfoListBySkuId(skuId);
    }
}
